package com.xsq.netty;

import com.xsq.netty.utils.LogUtils;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 心跳管理器
 */
public class NettyHeartbeatHandler extends ChannelHandlerAdapter {
    private final NettyConnection nettyConnection;

    public NettyHeartbeatHandler(NettyConnection nettyConnection) {
        this.nettyConnection = nettyConnection;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            switch (state) {
                case READER_IDLE: {
                    LogUtils.i(NettyHelper.TAG, String.format("客户端间隔%s没接收到服务器信息！", nettyConnection.getConfig().severOnResponseInterval));
                    // 规定时间内没收到服务端心跳包响应，进行重连操作
//                    nettyConnection.reconnect();
                    break;
                }

                case WRITER_IDLE: {
                    if (NettyClient.getInstance().isConnectServer()) {
                        LogUtils.i(NettyHelper.TAG, String.format("客户端间隔%s没发送信息！", nettyConnection.getConfig().heartbeatInterval));
                        // 规定时间内没向服务端发送心跳包，即发送一个心跳包
                        nettyConnection.sendMessage(nettyConnection.getConfig().heartbeatMsg);
                    }
                    break;
                }
            }
        }
    }

}
